//
//  RMWriteNoteViewController.m
//  RMNote
//
//  Created by lanou3g on 16/4/18.
//  Copyright © 2016年 lxf. All rights reserved.
//

#import "RMWriteNoteViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "RMAddImageView.h"
#import "RMweatherChangeView.h"
#import "RMnoteTextAttachment.h"
#import "NSDate+Calendar.h"
#import "RMBaseModel.h"
#import "RMDateBaseManager.h"
//#import <UMSocial.h>
//#import "RMLocationManager.h"

@interface RMWriteNoteViewController ()<UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UITextViewDelegate>{

}

@property (weak, nonatomic) IBOutlet UIButton *weatherButton;

@property (weak, nonatomic) IBOutlet UITextField *titleTextField;

@property (weak, nonatomic) IBOutlet UITextView *noteTextView;

@property (weak, nonatomic) IBOutlet UITextField *addressTextField;

@property (weak, nonatomic) IBOutlet UILabel *dateLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomDistanceAboutTextView;

@property(nonatomic,strong)UIActionSheet * actionSheet;

@property(nonatomic,strong)NSMutableArray * weatherImageArray;

@property(nonatomic,strong)NSMutableArray * pictureArray;

@property(nonatomic)RMAddImageView * addImageView;

@property(nonatomic,assign)BOOL istitleTextFieldRespond;
@property(nonatomic,assign)BOOL isaddressTextFieldRespond;
@property(nonatomic,assign)BOOL isNoteTextViewFirstRespond;
@property(nonatomic,strong)RMweatherChangeView * weatherView ;
@property(nonatomic,assign)CGRect keyboardFrame;
@end

@implementation RMWriteNoteViewController

-(NSMutableArray *)pictureArray{
    if (_pictureArray == nil) {
        _pictureArray = [[NSMutableArray alloc]initWithCapacity:1];
    }
    return _pictureArray;
}

- (void)viewDidAppear:(BOOL)animated
{
//     测试使用
//    NSArray *arr = [[RMDateBaseManager defaultManager]selectNoteFromTable:kRMNoteTable];
//    self.baseModel = [arr lastObject];

    if (!self.baseModel) {
        return;
    }
    if (self.noteTextView.text.length > 0) {
        return;
    }
    
    [self.weatherButton setImage:[UIImage imageWithData:self.baseModel.weather] forState:(UIControlStateNormal)];
    self.titleTextField.text = self.baseModel.title;
    self.noteTextView.text = self.baseModel.content;
    self.pictureArray = self.baseModel.picArr .mutableCopy;
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:self.noteTextView.attributedText];
    for (NSDictionary * dic in self.baseModel.picArr) {
        NSNumber * loc =[dic objectForKey:@"location"];
        NSNumber * imgHW = [dic objectForKey:@"imageH_W"];
        UIImage *image = [dic objectForKey:@"image"];
        RMnoteTextAttachment *textAttachment= [[RMnoteTextAttachment alloc]init];
        textAttachment.scaleImage = imgHW.floatValue;
        textAttachment.image = image;
        NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment];
        [string insertAttributedString:textAttachmentString atIndex:loc.integerValue];
        
    }
    
    self.noteTextView.attributedText = string;

    NSRange rang ;
    rang.length = string.length;
    rang.location = string.length;
    self.noteTextView.selectedRange = rang;
    
    self.addressTextField.text = self.baseModel.location;
    self.dateLabel.text = [NSString stringWithFormat:@"%@.%@.%@",self.baseModel.createDate.year,self.baseModel.createDate.month,self.baseModel.createDate.day];
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationItem setTitle:@"文本日记"];
     [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    //左button : 返回
    UIBarButtonItem * backButton = [UIBarButtonItem itemWithImage:@"back"  hightImage:@"back_hl" target:self action:@selector(backMainVCAction)];
    self.navigationItem.leftBarButtonItem = backButton;
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor redColor];
    //右button : 完成
        UIBarButtonItem * finishButton = [UIBarButtonItem itemWithImage:@"finish" hightImage:@"finish_hl"target:self action:@selector(writeDoneAction)];
     UIBarButtonItem * pictureBtn = [UIBarButtonItem itemWithImage:@"picture"  hightImage:@"picture_hl" target:self action:@selector(addPictureButton:)];
      UIBarButtonItem * shareButton = [UIBarButtonItem itemWithImage:@"share" hightImage:@"share_hl"target:self action:@selector(shareButton)];
    
    self.navigationItem.rightBarButtonItems = @[finishButton,pictureBtn];
    self.noteTextView.delegate = self;
 
    //mark!!!:给键盘添加通知中心
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyboardNotification:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyboardNotification:) name:UIKeyboardWillShowNotification object:nil];
    _isNoteTextViewFirstRespond = YES;
    _isaddressTextFieldRespond = YES;
    _istitleTextFieldRespond = YES;
    //获取本地日期
    [self getLocationDate];
    //开始定位
    [self getLocation];
}

- (void)getLocation{
//    [[RMLocationManager defaultManager]getLocation_complete:^(NSString *location) {
//        self.addressTextField.text = location;
//    } error:^(NSError *error) {
//
//        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"定位失败" message:@"请前往系统设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil];
//        UIAlertAction * settingAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            //UIApplicationOpenSettingsURLString 系统提供进入设置页面路径
//            NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
//            // 判断是否能跳转设置页面
//            if ([[UIApplication sharedApplication] canOpenURL:url]) {
//                // 如果能,跳转
//                [[UIApplication sharedApplication] openURL:url];
//            }
//        }];
//        [alertController addAction:cancelAction];
//        [alertController addAction:settingAction];
//        [self presentViewController:alertController animated:YES completion:nil];
//
//        NSLog(@"定位失败,%@",error);
//
//
//
//    }];
}

//移除通知中心
-(void)dealloc{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}
//mark!!!:获取本地日期
-(void)getLocationDate{
    NSDate * locationDate = [NSDate date];
    self.dateLabel.text = [NSString stringWithFormat:@"%@.%@.%@",[locationDate year],[locationDate month],[locationDate day]];
//    self.noteTextView.text = [NSString stringWithFormat:@"%@",locationDate];
}
//mark!!!:返回按钮
-(void)backMainVCAction{

    if (!self.baseModel) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
//    if ([self.baseModel.title isEqualToString:self.titleTextField.text]&&[self.baseModel.content isEqualToString:self.noteTextView.text]&&[self.baseModel.noteContent isEqualToAttributedString:self.noteTextView.attributedText]&&[self.baseModel.location isEqualToString:self.addressTextField.text]) {
//        [self.navigationController popViewControllerAnimated:YES];
//        return;
//    }
    
    if ([self.baseModel.noteContent isEqualToAttributedString:self.noteTextView.attributedText]) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"" message:@"是否保存当前更改" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"不保存" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self saveNote];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
    
    
    
}
//mark!!!:点击完成时,rightButton变为编辑,并用户不可再操作textView
-(void)writeDoneAction{

    self.noteTextView.editable = YES;
    self.titleTextField.enabled = YES;
    self.addImageView.userInteractionEnabled = YES;
    self.weatherButton.userInteractionEnabled = YES;
    
    [self saveNote];
    [self.navigationController popViewControllerAnimated:YES];
    
}


#pragma mark ----实现  UITextViewDelegate 的代理方法
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [self.noteTextView flashScrollIndicators];
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    [self.noteTextView flashScrollIndicators];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView
{
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:self.noteTextView.attributedText];
    NSRange rang;
    rang.location = 0;
    rang.length = string.length;
    [string enumerateAttribute:@"NSAttachment" inRange:rang options:NSAttributedStringEnumerationReverse usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
        
        NSLog(@"%@",value);
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *dic in self.pictureArray) {
           NSTextAttachment *textatt = [dic objectForKey:@"NSTextAttachment"];
            if (textatt == value) {
                [arr addObject:dic];
            }
        }
        self.pictureArray = arr;
        
    }];

    //让编辑状态下如果实际内容大于显示区域，滚动条一直存在
    [self.noteTextView flashScrollIndicators];
}


//mark!!!:键盘
- (void)onKeyboardNotification:(NSNotification *)notification {

    if ([notification.name isEqualToString:UIKeyboardWillShowNotification]) {
        _isNoteTextViewFirstRespond = YES;
        CGRect keyboardFrame = ((NSValue *) notification.userInfo[UIKeyboardFrameEndUserInfoKey]).CGRectValue;
        self.keyboardFrame = keyboardFrame;
        _bottomDistanceAboutTextView.constant = keyboardFrame.size.height + 50;
        NSLog(@"--------%f",_bottomDistanceAboutTextView.constant);
       
    } else if ([notification.name isEqualToString:UIKeyboardWillHideNotification]) {
        _isNoteTextViewFirstRespond = YES;
        _bottomDistanceAboutTextView.constant = 50;
        if (self.navigationController.isNavigationBarHidden == YES ) {
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }

    }
    [self.view layoutIfNeeded];

    
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.noteTextView resignFirstResponder];
    [self.titleTextField resignFirstResponder];
    [self.addressTextField resignFirstResponder];

}
//mark!!!:选图片
- (void)addPictureButton:(id)sender {
    [self getPictureFromLocation];
}

//mark!!!:获取本地相册,调用相机,选择图片
-(void)getPictureFromLocation{
    [self.noteTextView resignFirstResponder];
    [self.titleTextField resignFirstResponder];
    [self.addressTextField resignFirstResponder];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        self.actionSheet = [[UIActionSheet alloc]initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从手机相册选择", nil];
    }else{
    
        self.actionSheet = [[UIActionSheet alloc]initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从手机相册选择", nil];
    }

    self.actionSheet.tag = 1000;
    [self.actionSheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (actionSheet.tag == 1000) {
        NSInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //判断是否支持拍照
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] ) {
            switch (buttonIndex) {
                case 0:
                    //图片来源于相机拍照
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //图片来源于本地相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    return;
            }
        }else{
//            NSLog(@"%d",buttonIndex);
        if (buttonIndex == 1) {
            return;
        }else{
           sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        }
    }
        //跳转到相机或相册页面
        UIImagePickerController * imagePickerController = [[UIImagePickerController alloc]init];
        imagePickerController.delegate = self;
        imagePickerController.sourceType = sourceType;
        [self presentViewController:imagePickerController animated:YES completion:nil];
   }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
         [UIApplication sharedApplication].statusBarHidden = NO;
         NSString * mediaType = [info objectForKey:UIImagePickerControllerMediaType];
         NSData * data;
    if ([mediaType isEqualToString:@"public.image"]) {
        UIImage * originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        //将图片转换为JPG格式的二进制数据
        data = UIImageJPEGRepresentation(originImage, 0.5);
        //将二进制数据生成Image
        UIImage * image = [UIImage imageWithData:data];
        //图片的宽高比
        CGFloat imageH_W = image.size.height / image.size.width;
        if (imageH_W > 1.25) {
            imageH_W = 1.25;
        }
        //mark!!!: 图片压缩长宽
        UIImage * scaleImage = [self scaleToSize:image size:CGSizeMake(kScreenWidth - 50, (kScreenWidth - 50 ) * imageH_W)];
        NSLog(@"**********************%f  %f",image.size.width,image.size.height);
        NSLog(@"----------------------%f  %f",scaleImage.size.width,scaleImage.size.height);
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:self.noteTextView.attributedText];
        RMnoteTextAttachment *textAttachment = [[RMnoteTextAttachment alloc]init];
        textAttachment.scaleImage = imageH_W;
        textAttachment.image = scaleImage;
        NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment] ;
        //index为用户指定要插入图片的位置
        [string insertAttributedString:textAttachmentString atIndex:self.noteTextView.selectedRange.location];
        
        NSNumber * loc = [NSNumber numberWithInteger:self.noteTextView.selectedRange.location];
        NSNumber *imgHW = [NSNumber numberWithFloat:imageH_W];

        [self.pictureArray addObject:@{@"image":scaleImage,@"location":loc,@"imageH_W":imgHW,@"NSTextAttachment":textAttachment}];
   
        self.noteTextView.attributedText = string;
        self.noteTextView.font = [UIFont systemFontOfSize:kRealValue(20)];
//        NSRange rang;
//        rang.location = 0;
//        rang.length = string.length;
//        
//        [string enumerateAttributesInRange:rang options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
//            NSLog(@"%@ ---%@",attrs,rang);
//            
//            
//        }];
        
        //隐藏uiimagepickercontroller本身的导航栏
        picker.navigationBar.hidden = NO;
        [picker dismissViewControllerAnimated:YES completion:nil];
        picker = nil;
    }
}
//mark!!!: 图片压缩
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}
 //mark!!!:天气选择
- (IBAction)changeWeatherAction:(id)sender {
    if (self.weatherView) {
        return;
    }
    __weak RMWriteNoteViewController * RMwriteVC = self;
    self.weatherView = [[[NSBundle mainBundle]loadNibNamed:@"RMweatherChangeView" owner:nil options:nil]lastObject];
    self.weatherView.frame = CGRectMake(CGRectGetMinX(self.noteTextView.frame), CGRectGetMaxY(self.weatherButton.superview.frame), 200, 200);
    self.weatherView.weatherSelectBlock = ^(UIImage * weatherImage){
        [RMwriteVC.weatherButton setImage:weatherImage forState:(UIControlStateNormal)];
        [RMwriteVC.weatherView removeFromSuperview];
        RMwriteVC.weatherView = nil;
        RMwriteVC.titleTextField.userInteractionEnabled = YES;
        RMwriteVC.noteTextView.userInteractionEnabled = YES;
        RMwriteVC.addressTextField.userInteractionEnabled = YES;
    };
    [self.view addSubview:self.weatherView];
    self.weatherView.userInteractionEnabled = YES;
    self.titleTextField.userInteractionEnabled = NO;
    self.noteTextView.userInteractionEnabled = NO;
    self.addressTextField.userInteractionEnabled = NO;
    
}




#pragma mark ----存数据

-(void)saveNote{
    [[RMDateBaseManager defaultManager]createTable:kRMNoteTable];
    if (!self.baseModel) {
        self.baseModel = [[RMBaseModel alloc]init];
        self.baseModel.title = self.titleTextField.text;
        self.baseModel.noteContent = self.noteTextView.attributedText;
        self.baseModel.content = self.noteTextView.text;
        self.baseModel.location = self.addressTextField.text;
        self.baseModel.weather = UIImagePNGRepresentation(self.weatherButton.currentImage);
        self.baseModel.createDate = [NSDate date];
        self.baseModel.picArr = self.pictureArray;
        [[RMDateBaseManager defaultManager]insertIntoTable:kRMNoteTable createDate:self.baseModel.createDate Model:self.baseModel];
    }else{

        self.baseModel.title = self.titleTextField.text;
         self.baseModel.noteContent = self.noteTextView.attributedText;
        self.baseModel.location = self.addressTextField.text;
        self.baseModel.weather = UIImagePNGRepresentation(self.weatherButton.currentImage);
        self.baseModel.content = self.noteTextView.text;
        
        self.baseModel.picArr = self.pictureArray;
        [[RMDateBaseManager defaultManager]updateNoteFromTableName:kRMNoteTable withModel:self.baseModel byCreateDate:self.baseModel.createDate];
    }
}



//弹出列表方法presentSnsIconSheetView需要设置delegate为self
-(BOOL)isDirectShareInIconActionSheet
{
    return YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
